package com.example.lijuan.myapplication.UI.Fragment;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.maps2d.model.LatLng;
import com.example.lijuan.myapplication.Adapter.TripHistoryListAdapter;
import com.example.lijuan.myapplication.R;
import com.example.lijuan.myapplication.Service.TripServices;
import com.example.lijuan.myapplication.Util.Constants;
import com.example.lijuan.myapplication.module.Location;
import com.example.lijuan.myapplication.module.Trip;
import com.example.lijuan.myapplication.module.TripSummary;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.List;

import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;

import java.util.ArrayList;
import java.util.List;


/**
 * Class com.sita.bike.ui.fragments is for
 *
 * @author mark on 15/5/26.
 */
public class FragmentTripHistoryList extends Fragment{

    private RecyclerView mTripHistoryListView;
    private TripHistoryListAdapter mAdapter;
    private List<Location> points;
    private Trip trip_one,trip_two,trip_three;

    public static FragmentTripHistoryList newInstance() {
        return new FragmentTripHistoryList();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
   }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trip_list, container, false);
        mTripHistoryListView = (RecyclerView) view.findViewById(R.id.trip_history_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mTripHistoryListView.setLayoutManager(layoutManager);

        Location location0 = new Location();
        location0.setLatitude(String.valueOf(39.157419));
        location0.setLongitude(String.valueOf(117.334671));
        Location location1 = new Location();
        location1.setLatitude(String.valueOf(39.161612));
        location1.setLongitude(String.valueOf(117.370462));
        Location location2 = new Location();
        location2.setLatitude(String.valueOf(39.162877));
        location2.setLongitude(String.valueOf(117.385826));
        Location location3 = new Location();
        location3.setLatitude(String.valueOf(39.157985));
        location3.setLongitude(String.valueOf(117.39001));
        Location location4 = new Location();
        location4.setLatitude(String.valueOf(39.160032));
        location4.setLongitude(String.valueOf(117.395289));
        points = new ArrayList<>();
        points.add(location0);
        points.add(location1);
        points.add(location2);
        points.add(location3);
        points.add(location4);
        trip_one = new Trip();
        trip_one.setLocations(points);
        trip_one.setArriveTime("2015-09-10");
        trip_one.setFromTime("2015-09-09");
        trip_two = new Trip();
        trip_two.setLocations(points);
        trip_two.setArriveTime("2015-10-07");
        trip_two.setFromTime("2015-10-06");
        trip_three = new Trip();
        trip_three.setLocations(points);
        trip_three.setArriveTime("2015-10-12");
        trip_three.setFromTime("2015-10-11");


//        String model = "$TUAPAD";
//        String idn = "DEMO_A00A000002";
//        long deviceId = 1L;
//        TestDataSRDProvider dataProvider = new TestDataSRDProvider(model, idn, deviceId);
//        DateTime start1 = DateTime.now();
//        DateTime end1 = start1.plusMinutes(3);
//        DeviceTrip deviceTrip1 = dataProvider.getDeviceTrip(start1.toDate(), end1.toDate());
//
//        DateTime start2 = start1.plusHours(1);
//        DateTime end2 = start2.plusMinutes(3);
//        DeviceTrip deviceTrip2 = dataProvider.getDeviceTrip(start2.toDate(), end2.toDate());
//
//        List<DeviceTrip> deviceTrips = Lists.newArrayList(deviceTrip1, deviceTrip2);




        List<Trip> trips = new ArrayList<>() ;
        trips.add(trip_one);
        trips.add(trip_two);
        trips.add(trip_three);


        mAdapter = new TripHistoryListAdapter(getActivity(), trips);
        mAdapter.setOnItemButtonClickListener(new TripHistoryListAdapter.OnItemButtonClickListener() {
            @Override
            public void onItemButtonClick(View itemView, int position) {
                Trip trip = mAdapter.getItem(position);


                FragmentCarTrip fct = new FragmentCarTrip();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                Bundle bundle = new Bundle();
                bundle.putSerializable("trips",trip);
                fct.setArguments(bundle);
                ft.replace(R.id.fragment_car_trip, fct);
                ft.commit();

            }
        });
        mTripHistoryListView.setAdapter(mAdapter);
        setUpTripHistory();
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        menu.clear();
//
//        inflater.inflate(R.menu.contact_menu_bar, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.action_contact_mgr: {
//
//                View menuItemView = getActivity().findViewById(R.id.action_contact_mgr);
//                PopupMenu popupMenu = new PopupMenu(getActivity(), menuItemView);
//                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//                    public boolean onMenuItemClick(MenuItem item) {
//
//                        doAction(item.getItemId());
//                        return true;
//                    }
//
//                });
//                popupMenu.inflate(R.menu.contact_menu_list);
//                popupMenu.show();
//            }
//        }
//
//        return (super.onOptionsItemSelected(item));
//    }


//    private class PerformAddContactTask extends AsyncTask<PendingContact, Void, Void> {
//        int mPosition;
//
//        PerformAddContactTask(int position) {
//            mPosition = position;
//        }
//
//        @Override
//        protected Void doInBackground(PendingContact... params) {
//            PendingContact pendingContact = params[0];
//            PersistUtils.movePendingContactToContact(pendingContact);
//            return null;
//        }
//
//        @Override
//        protected void onPostExecute(Void param) {
//            mAdapter.updatePendingContactStatus(mPosition, Constants.PENDING_CONTACT_REQUEST_BY_ME);
//        }
//    }

    private void setUpTripHistory() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("Content-Type", "application/json").addHeader("header", Constants.ACCEPT).build();
                return chain.proceed(request);
            }
        };
        // Add the interceptor to OkHttpClient
        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(interceptor);

        // Set the custom client when building adapter
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.SERVER_ADDRESS)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        //
        TripServices tripServices = retrofit.create(TripServices.class);
        Call<List<Trip>> call = tripServices.getTripHistory("CAR_A00A000002");
        call.enqueue(new Callback<List<Trip>>() {

            @Override
            public void onResponse(retrofit.Response<List<Trip>> response, Retrofit retrofit) {
                System.out.println("TripHistory : " + response.toString());
                // update UI
//                textViewLastTripMile.setText(getString(R.string.trip_summary_mile) + " " + Double.toString(tripSummary.getTotalMileage()) + getString(R.string.km));
//                textViewLastTripDate.setText(getString(R.string.trip_summary_date) + Double.toString(tripSummary.getThisMileage()));
//                textViewLastTripTime.setText(getString(R.string.trip_summary_time) + " " + formatTime(tripSummary.getThisDriveTime()));
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("Error : " + t.toString());
            }

            private String formatTime(double second)
            {
                String result = "";
                int hour = (int) (second / 3600);
                int minute = (int) ((second - hour * 3600)/ 60);
                result = Integer.toString(hour) + getString(R.string.hour) + Integer.toString(minute) + getString(R.string.minute);
                return result;
            }
        });


    }
}
